package net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Scanner;

/**
 * 多点广播
 * @author FX_PC
 *
 */
public class Multicast implements Runnable{
	
	private final String BROADCAST_IP="230.0.0.1";  //广播地址
	private final int BROADCAST_PORT=30000;  //广播端口
	private final int DATA_LEN =4000;
	private MulticastSocket socket;
	private InetAddress broadcastAddress;
	
	//接受包裹
	byte[] inBuf=new byte[DATA_LEN];
	private DatagramPacket inPacket= new DatagramPacket(inBuf, inBuf.length);		
	// 发送包裹
	private DatagramPacket outPacket;
	
	public void init() {
		Scanner scan= new Scanner(System.in);
		try {
			socket = new MulticastSocket(BROADCAST_PORT);
			broadcastAddress = InetAddress.getByName(BROADCAST_IP);
			//加入广播
			socket.joinGroup(broadcastAddress);
			socket.setLoopbackMode(false);
			outPacket = new DatagramPacket(new byte[0], 0,broadcastAddress,BROADCAST_PORT);
			new Thread(this).start();
			
			while (scan.hasNextLine()) {
				byte buff[]=scan.nextLine().getBytes();
				outPacket.setData(buff);
				socket.send(outPacket);  //用户输入的群发
			}
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				socket.receive(inPacket);
				System.out.println("聊天信息:"+new String(inBuf,0,inPacket.getLength()));
			} catch (IOException e) {
				e.printStackTrace();
				try {
					socket.leaveGroup(broadcastAddress);
					socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			
		}
	}
	
	
	
	public static void main(String[] args) {
		new Multicast().init();
	}

}
